<template>
  <!-- <a-modal v-model="visible" destroyOnClose centered :footer="null"  :closable="false"> -->
    <div>
    <!-- <div class="n-dialog-mask"></div> -->
    <div class="n-dialog-container private-letter-modal">
      <!-- <a-button type="primary">
      Open Modal with async logic
    </a-button> -->
      <div class="prv-lt">
        <div class="tit">私信</div>
        <ul class="prv-ul-data">
          <li :class="{'cur':msgType==1}" @click="choseMsgType(1)">
                <div class="img-box">
                <img loading="lazy" :src="defaultAvatar" alt="">
                </div>
                <div class="info">
                <div class="info-tit">系统通知</div>
                <div class="desc">{{sysNoticeList.length>0?sysNoticeList[0].htitle:'暂无通知'}}</div>
                </div>
          </li>
          <li v-for="(g, gdx) in groups" :key="gdx" @click="handlePrivateTo(g, gdx)" :class="{ 'cur': gdx == curGdx&&msgType==2 }">
            <template v-if="userId == g.receiveId">
              <div class="img-box">
                <img loading="lazy" v-aimgd="{ avatar: g.sendMember.avatar, id: g.sendMember.id, w: 50, name: g.sendName }" @error="loadError">
              </div>
              <div class="info">
                <div class="info-tit">{{ g.sendName }}</div>
                <div class="desc" v-html="g.lastMessages
                    ? g.lastMessages.content
                    : g.content
                  "></div>
              </div>
            </template>
            <template v-else>
              <div class="img-box">
                <img loading="lazy" v-aimgd="{ avatar: g.receiveMember.avatar, id: g.receiveMember.id, w: 50, name: g.receiveMember.userName }" @error="loadError">
              </div>
              <div class="info">
                <div class="info-tit">{{ g.receiveMember.userName }}</div>
                <div class="desc" v-html="g.lastMessages
                    ? g.lastMessages.content
                    : g.content
                  "></div>
              </div>
            </template>
          </li>
          <!-- <li>
                <div class="img-box">
                <img loading="lazy" src="https://image.gameuiux.cn/2022/09/30/1664467790270u=614515080,2288269124&fm=224&app=112&f=JPEG.jpg" alt="">
                </div>
                <div class="info">
                <div class="info-tit">熊猫在奥西</div>
                <div class="desc">期待更多的作品</div>
                </div>
            </li>
            <li>
                <div class="img-box">
                <img loading="lazy" src="https://image.gameuiux.cn/2022/09/30/1664467790270u=614515080,2288269124&fm=224&app=112&f=JPEG.jpg" alt="">
                </div>
                <div class="info">
                <div class="info-tit">熊猫在奥西</div>
                <div class="desc">哈哈哈哈，跑的有点喘</div>
                </div>
            </li>-->
        </ul>
      </div>
      <div class="prv-rt-modalcon" v-show="msgType == 1">
        <div class="prvrt-header">
          <div class="tit">系统通知</div>
          <a class="close-btn" @click="$emit('close')"></a>
        </div>
        <div class="sys-notice-data custom-scroll" @scroll="onScroll">
          <ul >
            <li v-for="(c,idx) in sysNoticeList" :key="idx" :class="{'collapse':id==c.id}">
              <div class="tit" @click="chooseCollapse(c)"><div class="tit-val">{{c.htitle}}</div><span class="time-box">{{c.createTime}}<a class="collapse-btn"></a></span></div>
              <div class="con" v-html="c.content">
              </div>
              <div class="collapse-area">
                <a class="collapse-btn" @click="id=''">收起</a>
              </div>
            </li>
            <!-- <li class="flex-single">
              <div class="tit">错过就要再等一年～</div>
              <div class="time-area">
                <span class="time">2022年11月30日</span>
                <a class="open-btn"></a>
              </div>
            </li>
            <li class="flex-single">
              <div class="tit">【速来】参与活动天天抽奖</div>
              <div class="time-area">
                <span class="time">2022年11月30日</span>
                <a class="open-btn"></a>
              </div>
            </li>
            <li class="flex-single">
              <div class="tit">真的超级可以，GAMEUI 2022 设计大会～首次举办再…</div>
              <div class="time-area">
                <span class="time">2022年11月30日</span>
                <a class="open-btn"></a>
              </div>
            </li>
            <li class="flex-single">
              <div class="tit">HI~魔触！AI大法等你来～</div>
              <div class="time-area">
                <span class="time">2022年11月30日</span>
                <a class="open-btn"></a>
              </div>
            </li> -->
          </ul>
        </div>
      </div>
      <div class="prv-rt-modalcon" v-show="msgType == 2">
        <div class="prvrt-header">
          <div class="tit has-action"  v-if="groups.length>0">
            <span class="desc-txt">与
              {{ groups.length > 0 ? (groups[curGdx].receiveId == userId ? groups[curGdx].sendName : groups[curGdx].receiveName) : '' }}
              的私信{{ groups[curGdx].id }}</span>
            <a class="more-dwns" v-if="groups[curGdx].id">
              <i class="dwns-btn"></i>
              <ul class="dwns-items">
                <li><a @click="curId=groups[curGdx].id;showShield=true;">屏蔽此人</a></li>
                <li><a @click="curId=groups[curGdx].id;showDelConfirm=true;">删除对话</a></li>
                <li><a @click="handleReport">举报</a></li>
              </ul>
            </a>
          </div>
          <a class="close-btn" @click="$emit('close')"></a>
        </div>
        <ul class="prv-rt-messages" id="msgBox">
          <template v-for="(m, mdx) in gConversation">
            <template v-if="m">
              <li class="rt-msg" v-if="userId == m.sendId" :key="mdx">
                <div class="msg-time">{{ m.createTime }}</div>
                <div class="msg-item">
                  <div class="msg-con" v-html="m.content">
                  </div>
                  <div class="user-img">
                    <img loading="lazy" v-aimgd="{ avatar: m.sendMember.avatar, id: m.sendMember.id, w: 50, name: m.sendName }"  @error="loadError">
                  </div>
                </div>
              </li>
              <li class="lt-msg" v-else>
                <div class="msg-time">{{ m.createTime }}</div>
                <div class="msg-item">
                  <div class="user-img">
                    <img loading="lazy" v-aimgd="{ avatar: m.sendMember.avatar, id: m.sendMember.id, w: 50, name: m.sendName }"  @error="loadError">
                  </div>
                  <div class="msg-con" v-html="m.content">
                  </div>
                </div>
              </li>
            </template>
          </template>


          <!-- <li class="rt-msg">
              <div class="msg-item">
                  <div class="msg-con">
                  good！棒～
                  </div>
                  <div class="user-img">
                  <img loading="lazy" src="https://image.gameuiux.cn/2022/09/30/1664467790270u=614515080,2288269124&fm=224&app=112&f=JPEG.jpg" alt="">
                  </div>
              </div>
              </li> -->
        </ul>
        <div class="input-msg-box">
          <textarea id="msg_input" class="msg-input" :class="{ 'active': isFocus }" @focus="isFocus = true" @blur="isFocus = false"
            v-model="msgCon" placeholder="请输入消息"></textarea>
          <a class="send-btn" @click="handleSend"></a>
        </div>
      </div>
    </div>
    <a-modal v-model="showFeedBack" destroyOnClose centered :footer="null" :zIndex="10001"  :closable="false" width="670px">
      <FeedBack ref="refFeedBack" :targetid="targetId" :targettype="0" @close="showFeedBack=false"/>
    </a-modal>

    <a-modal v-model="showDelConfirm" destroyOnClose centered :zIndex="10001" :footer="null" :closable="false" width="366px">
        <div class="fav-component" >
            <div class="fav-header">
                系统提示
            </div>
            <div class="folder-con" style="margin-top:30px;text-align:center;font-size:14px;">
                确定要删除此对话？
            </div>
            <div class="btns m-widbtns">
                <a class="pro-default-btn" @click="showDelConfirm=false">取消</a>
                <a class="pro-confirm-btn" @click="handleDel">确认</a>
            </div>
        </div>
    </a-modal>

    <a-modal v-model="showShield" destroyOnClose centered :zIndex="10001" :footer="null" :closable="false" width="366px">
        <div class="fav-component" >
            <div class="fav-header">
                系统提示
            </div>
            <div class="folder-con" style="margin-top:30px;text-align:center;font-size:14px;">
                确定要屏蔽？
            </div>
            <div class="btns m-widbtns">
                <a class="pro-default-btn" @click="showShield=false">取消</a>
                <a class="pro-confirm-btn" @click="handleShield">确认</a>
            </div>
        </div>
    </a-modal>
  </div>
  <!-- </a-modal> -->
</template>

<script>
import FeedBack from '@/components/feedBack'
import SparkMD5 from 'spark-md5'
import api from '@/api/api'
export default {
  data() {
    return {
      targetId:'',
      defaultAvatar:require('@/assets/pro/default_sys_img.svg'),
      defaultUserAvatar:require('@/assets/pro/default_sys_img.svg'),
      curId:'',
      showShield:false,
      showDelConfirm:false,
      showFeedBack:false,
      totalP:0,
      id:'',
      sysNoticeList:[],
      hasSysMore:true,
      sysNoticeQuery:{
        orderByColumn:'createTime',
        isAsc:'desc',
        pageNum:1,
        pageSize:10,
        type:0
      },
      visible:false,
      isFocus: false,
      msgCon: '',
      userId: '',
      userInfo: {},
      curGdx: 0,
      gConversation: [],
      msgType: 1,
      groups: [],
      targetMember: {}
    }
  },
  components:{FeedBack},
  methods: {
    loadError(e){
      e.target.src=this.defaultUserAvatar;
      e.target.removeAttribute('srcset');
    },
    handleReport(){
      let item=this.groups[this.curGdx];
      this.targetId=item.sendId==this.userId?item.receiveId:item.sendId;
      this.showFeedBack=true;
    },
    chooseCollapse(item){
      if(this.id==item.id)this.id=''
      else this.id=item.id;
    },
    onScroll(e){
      let spacNum = e.target.scrollHeight - ($(e.target).scrollTop() + $(e.target).height())
      if (spacNum < 1 && this.totalP != this.sysNoticeQuery.pageNum&&this.hasSysMore) {
        this.sysNoticeQuery.pageNum++
        this.querySysNoticeList()
      }
    },
    async querySysNoticeList(){
      let res=await api.noticesList(this.sysNoticeQuery);
      let textRegex = /(?<=>)[^<]+(?=<)/g;
      textRegex=/<[^>]*>|&nbsp;/g;
      res.data.map(item=>{
        item.iscollapse=false;
        // if(item.content&&item.content.match(textRegex))
          item.htitle=item.content.replace(textRegex,'');
      })
      
      let rsnum = res.total % this.sysNoticeQuery.pageSize;
      let totalPage= rsnum == 0 ? res.total / this.sysNoticeQuery.pageSize : parseInt(res.total / this.sysNoticeQuery.pageSize + 1);
      this.hasSysMore=!(res.data && (res.data.length < this.sysNoticeQuery.pageSize || this.sysNoticeQuery.pageNum >= totalPage));
      this.sysNoticeList=[...this.sysNoticeList,...res.data];
      this.totalP=totalPage;
    },
    choseMsgType(_type){
      this.sysNoticeQuery.pageNum=1;
      this.sysNoticeList=[];
      this.msgType=1;
      this.querySysNoticeList();
    },
    async handleShield() {
      let item = this.groups[this.curGdx];
      let res = await api.shieldTo(item.id);
      if(res.code==0){
        this.showShield=false;
        this.curId='';
        this.$amessage.success('屏蔽成功')
      }
    },
    async handleDel() {
      let item = this.groups[this.curGdx];
      let res = await api.delPrivate(item.id);
      if(res.code==0){
        this.showDelConfirm=false;
        this.curId='';
        this.groups.splice(this.curGdx,1);
        this.$amessage.success('删除成功');
        if(this.groups.length>0){
          this.handlePrivateTo(this.groups[0],0);
        }else{
          this.msgType=1;
        }
      }
    },
    async handleSend() {
      if (!this.msgCon) return;
      let res = {};
      if (!this.targetMember.lastMessages) {
        res = await api.sendPrivateMsg({ receiveId: this.privatemember.id, content: this.msgCon })
      }
      else {
        let _item = this.groups[this.curGdx];
        res = await api.sendPrivateMsg({
          parentId: _item.id, receiveId: this.userId == _item.receiveId
            ? _item.sendId
            : _item.receiveId, content: this.msgCon
        })
      }
      if (res.code == 0) {
        if (this.privatemember) {
          res.data.receiveMember = this.privatemember;
        }
        res.data.sendMember = this.userInfo;
        this.gConversation.push(res.data);
        this.groups[this.curGdx].id=res.data.id;
        this.groups[this.curGdx].lastMessages = { content: this.msgCon };
        this.groups[this.curGdx].content = this.msgCon;
        this.msgCon = '';
        this.$nextTick(() => {
          $("#msgBox").animate({ scrollTop: 9999 }, 1000)
        });
      }
    },
    onImgError(e) {
      e.target.src = require('../assets/pro/default_uimg.svg');
      e.target.srcset = require('../assets/pro/default_uimg.svg');
    },
    get_avatar_url(member = { id: '', avatar: '' }, n = 1, w = 30) {
      if (!member.id || !member.avatar) return this.defaultAvatar
      let hash = SparkMD5.hash(member.avatar).slice(0, 6)
      return `https://img.gameui.net/avatar-${member.id}-${hash}@${n}x${w}.webp`
    },
    get_avatar_urls(member = { id: '', avatar: '' }, w = 30) {
      return `${this.get_avatar_url(member, 1, w)} 1x, ${this.get_avatar_url(member, 2, w)} 2x, ${this.get_avatar_url(member, 3, w)} 3x`
    },
    handleClose() {
      this.$emit('close')
    },
    async queryMessagesById(_id) {
      let res = await api.getPrivateMessageList({ parentId: _id, orderByColumn: 'createTime', isAsc: 'asc', pageNum: 1, pageSize: 30 });

      if (res.data && res.data.length > 0) {
        this.gConversation = res.data;
        this.$nextTick(() => {
          $('#msg_input').focus();
          if ($("#msgBox>li").length > 0) {
            $("#msgBox").animate({ scrollTop: 9999 }, 300)
            //$("#msgBox").scrollTop(999999);
          }
        });
      }
    },
    handlePrivateTo(item, idx) {
      this.msgType=2;
      this.curGdx = idx;
      this.targetMember = item;
      if(item.id)
        this.queryMessagesById(item.id);
      else
        this.gConversation=[];
    }
  },
  props: ['privatemember'],
  destroyed() {
    // document.body.style.overflow = 'inherit';
  },
  async mounted() {
    this.userId = localStorage.getItem('userId');
    this.userInfo = JSON.parse(decodeURIComponent(localStorage.getItem('BSIC')))
    let res = await api.getPrivateGroups();
    this.groups = res.data;
    if (this.privatemember) {
      let newObj = Object.assign({}, this.privatemember);

      newObj.receiveId = this.privatemember.id;
      delete newObj.id;
      newObj.sendName = this.userInfo.userName;
      newObj.receiveName = this.privatemember.userName;
      newObj.privatemember = this.privatemember;
      newObj.receiveMember = this.privatemember;

      let isExist = false;

      let that = this;

      let newgroups = Object.assign([], this.groups);
      this.groups.map((item, idx) => {
        if (item.sendId == newObj.receiveId||item.receiveId == newObj.receiveId) {
          isExist = true;
          that.curGdx = 0;
          
          let result = newgroups.splice(idx, 1);
          result.id=item.id;
          newgroups = [...result, ...newgroups];
          that.groups = newgroups;
        }
      })
      if (!isExist)
        this.groups = [...[newObj], ...this.groups];
      
      this.targetMember = this.privatemember;
      this.msgType=2;

      if(this.groups[0].id)
        this.handlePrivateTo(this.groups[0],0)
    }
    else{
      this.choseMsgType(1);
    }
  }
}
</script>

<style scoped lang="less">
.private-letter-modal {
  display: flex;
  // width: 860px;
  min-height: 625px;
  left: calc((100% - 860px) / 2);
  border-radius: 30px;
  box-shadow: 0px 0px 12px 3px rgba(0, 0, 0, 0.3);
  overflow: hidden;

  .prv-lt {
    min-width: 250px;
    width: 250px;
    overflow: hidden;
    padding: 28px 12px 28px 13px;
    background: #2E2D31;

    .tit {
      font-size: 18px;
      color: #fff;
      font-weight: 500;
      line-height: 25px;
      margin-bottom: 27px;
      margin-left: 20px;
    }

    .prv-ul-data {
      max-height: 600px;
      overflow-y: auto;
      overflow-x: hidden;
      padding-right:5px;
      &:hover{
          &::-webkit-scrollbar {
              display: block;
          }
      }
      /*滚动条整体部分,必须要设置*/
      &::-webkit-scrollbar {
        width: 3px;
        height: 8px;
        background-color: transparent;
        display: none;
      }

      /*滚动条的轨道*/
      &::-webkit-scrollbar-track {
        background-color: transparent;
      }

      /*滚动条的滑块按钮*/
      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background-color: #626262;
      }

      /*滚动条的上下两端的按钮*/
      &::-webkit-scrollbar-button {
        height: 0;
      }

      /* 两个滚动条的交汇处 */
      &::-webkit-scrollbar-corner {
        background-color: transparent;
      }

      li {
        padding: 14px 15px;
        display: flex;
        align-items: center;
        cursor: pointer;
        width: 100%;

        .img-box {
          width: 50px;
          min-width: 50px;
          height: 50px;
          border-radius: 50px;
          overflow: hidden;
          margin-right: 13px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .info {
          width: 100%;

          .info-tit {
            font-size: 16px;
            font-weight: 500;
            color: #fff;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 82%;
          }

          .desc {
            font-size: 14px;
            color: #969696;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            width: 75%;
          }
        }

        &.cur {
          background: #1A1A1D;
          border-radius: 8px;
        }

        &:hover {
          background: #1A1A1D;
          border-radius: 8px;
        }
      }
    }
  }

  .prv-rt-modalcon {
    padding: 30px 20px;
    width:calc(100% - 250px);

    .prvrt-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height:22px;
      position: relative;
      margin-bottom:28px;

      // margin-bottom:30px;
      // border:1px solid red;
      .tit {
        font-size: 16px;
        font-weight: 500;
        color: #fff;
        // margin-bottom:28px;

        &.has-action {
          // margin-bottom:0px;
          display: flex;
          align-items: center;

          .desc-txt {}

          .more-dwns {
            position: relative;

            .dwns-btn {
              width: 32px;
              height: 32px;
              background: url('../assets/pro/a_arrow_down.svg') no-repeat;
              display: inline-block;
              background-size: 16px 16px;
              background-position: center;
              margin-left: 14px;
              top: 2px;
              position: relative;
            }

            .dwns-items {
              background: #2E2D31;
              border-radius:9px;
              padding: 16px 10px;
              font-size: 16px;
              position: absolute;
              left: 10px;
              top: 27px;
              display: none;
              box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.18);
              li {
                line-height: 43px;
                overflow: hidden;
                border-radius: 8px;

                a {
                  display: inline-block;
                  user-select: none;
                  padding: 0px 21px;
                  width: 100%;
                  height: 100%;
                  white-space: nowrap;
                  text-align: center;

                  &:hover {
                    background: #201D28;
                  }
                }
              }
            }

            &:hover {
              .dwns-items {
                display: inherit;
              }
            }
          }
        }
      }

      .close-btn {
        width: 18px;
        height: 18px;
        background: url('../assets/pro/close-win.svg') no-repeat;
        background-size: cover;
        margin-right: 10px;
        position: absolute;
        right:0px;
      }
    }

    .sys-notice-data {
      // padding: 0px 22px;
      height:590px;
      overflow-y:auto;
      ul{
        // padding: 0px 22px;
        background:#242327;
        // border:1px solid red;
      }
      li {
        margin-bottom: 15px;
        transition:.2s all linear;
        // border:1px solid red;
        padding:14px 22px;
        border-radius:8px;

        .con {
          font-size: 14px;
          color: #969696;
          line-height: 22px;
          margin-top:10px;
        }

        .collapse-area {
          border-top: 1px solid #323232;
          margin-top: 31px;
          padding-top: 14px;
          text-align: right;
          padding-bottom: 15px;

          .collapse-btn {
            font-size: 14px;
            color: #969696;
          }
        }

        .time-area {
          display: flex;
          align-items: center;
          white-space: nowrap;

          .time {
            font-size: 12px;
            color: #969696;
          }

          .open-btn {
            width: 16px;
            height: 16px;
            background: url('../assets/pro/a_arrow_down.svg') no-repeat;
            background-size: cover;
            margin-left: 3px;
          }
        }

        &.flex-single {
          display: flex;
          justify-content: space-between;
          align-items: center;
          line-height: 48px;
        }
      }
    }

    .prv-rt-messages {
      min-height: 500px;
      max-height: 500px;
      overflow-y: auto;
      padding-right: 20px;

      /*滚动条整体部分,必须要设置*/
      &::-webkit-scrollbar {
        width: 3px;
        height: 8px;
        background-color: transparent;
      }

      /*滚动条的轨道*/
      &::-webkit-scrollbar-track {
        background-color: transparent;
      }

      /*滚动条的滑块按钮*/
      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background-color: #626262;
      }

      /*滚动条的上下两端的按钮*/
      &::-webkit-scrollbar-button {
        height: 0;
      }

      /* 两个滚动条的交汇处 */
      &::-webkit-scrollbar-corner {
        background-color: transparent;
      }

      .msg-time {
        font-size: 12px;
        color: #969696;
        text-align: center;
        display: inline-block;
        width: 100%;
        margin-top: 18px;
        margin-bottom: 37px;
      }

      .msg-item {
        display: flex;
        align-items: center;
        width: 100%;

        .msg-con {
          background: #11CCB1;
          padding: 10px 15px;
          border-radius: 12px;
          color: #fff;
          font-size: 16px;
          max-width: 270px;
          word-break: break-all;
        }

        .user-img {
          width: 32px;
          height: 32px;
          border-radius: 32px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
      }

      li {
        margin-bottom: 36px;
        width: 100%;
      }

      .rt-msg {
        .msg-item {
          justify-content: flex-end;
          align-items: flex-start;
        }

        .msg-con {
          margin-right: 11px;
        }
      }

      .lt-msg {
        .msg-item {
          justify-content: flex-start;
        }

        .msg-con {
          margin-left: 11px;
          background: #242327;
        }
      }
    }

    .input-msg-box {
      position: relative;
      height: 90px;
      .msg-input {
        width: 100%;
        padding: 13px 16px;
        border: none;
        height:100%;
        background: #171719;
        color: #fff;
        font-size: 14px;
        border-radius: 12px;
        resize: none;
        // transition: .1s all linear;
        padding-right: 80px;
        &::-webkit-input-placeholder {
          color: #969696;
        }
        &.active {
          background: #171719;
          border:1px solid #11CCB1;
        }
      }

      .send-btn {
        width: 60px;
        height: 40px;
        background: url('../assets/pro/send_msg.svg') no-repeat;
        background-size: cover;
        position: absolute;
        right:10px;
        bottom:10px;
        opacity: .8;
        &:hover {
          opacity: 1;
        }
      }
    }
  }
}
</style>